package com.wink_172.library.view

import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.wink_172.library.callback.ICallback
import com.wink_172.library.model.Constants

/**
 * 倒计时优化版本
 */
class CountDownOptimizeView : AppCompatTextView {

    val msg_what = 100
    open var mCallback: ICallback? = null

    open var handler: MyHandler? = null

    inner class MyHandler : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                msg_what -> {
                    still_second -= 1;
                    if (still_second > 0) {
                        handler!!.sendEmptyMessageDelayed(msg_what, 1000)
                    }
                    if(mCallback!=null){
                        mCallback!!.onSendEvent(Constants.EventEnum.倒计时进行中.ordinal,still_second)
                    }
                }
            }
        }
    }


    constructor(context: Context?) : super(context!!) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!,
        attrs,

        defStyleAttr
    ) {
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        initView()

        handler = MyHandler()
    }

    private fun initView() {}

    /**
     * 初始化
     */
    open fun init(callback: ICallback) {
        mCallback=callback
    }

    var still_second = 0

    /**
     * 开始倒计时
     * still_second 剩余秒数
     * */
    open fun startCutDownTime(still_second: Int) {
        this.still_second = still_second
        handler!!.removeCallbacksAndMessages(null)
        handler!!.sendEmptyMessageDelayed(msg_what, 1000)
    }

    /**
     * 暂停倒计时
     */
    open fun pauseCutDownTime() {
        handler!!.removeCallbacksAndMessages(null)
    }

    /**
     * 恢复倒计时
     */
    open fun resumeCutDownTime() {
        handler!!.sendEmptyMessageDelayed(msg_what, 1000)
    }

    /**
     * 结束倒计时
     */
    open fun stopCutDownTime() {
        still_second=0
        handler!!.removeCallbacksAndMessages(null)
    }


}